<?php


namespace app\common\lib;

use app\common\cachemodel\Goods;
use app\common\cachemodel\ZlSynastryReport;
use app\common\lib\astrolog\SynastryReport as SynastryReportLib;
use app\common\model\MessageCenter;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use think\Env;
use think\Log;
use think\queue\Job;

class SynastryReportJob
{
    /**
     * 本命预测队列计算
     * @param Job $job
     * @param $jobData
     * @throws GuzzleException
     */
    public function task1(Job $job, $jobData): void
    {
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
        }

        $host = Util::getEcsIp();
        $startTime = date('Y-m-d H:i:s');
        $logInfo = "合盘报告计算 开始:{$startTime} host:{$host} 合盘报告ID:{$jobData['synastry_report_id']}";
//        print_r('合盘报告计算开始：' . $startTime . '合盘报告ID:' . $jobData['synastry_report_id'] . PHP_EOL);

        $now_time = time();
        $synastryReportId = (int)$jobData['synastry_report_id'];
        $recode1 = null;
        $recode2 = null;
        $synastryReportData = null;
        try
        {
            $SynastryReportModel = new ZlSynastryReport();
            $OrdersModel = new \app\common\cachemodel\Orders();
            $synastryReportData = $SynastryReportModel->where('id', $synastryReportId)
                ->field('uid,relation_id,gid,order_num,recode_info,start_time')
                ->findOrFail()->toArray();
            $recodeList = \GuzzleHttp\json_decode($synastryReportData['recode_info'], true);
            $recode1 = $recodeList['recode1']; // 档案1
            $recode2 = $recodeList['recode2']; // 档案2

            $goodsInfo = (new Goods())->getInfoById($synastryReportData['gid']);
            $startTime = $synastryReportData['start_time'];
            $endTime = strtotime($goodsInfo['expire_time'], $synastryReportData['start_time']);

            $synastryReportLib = (new SynastryReportLib())->setRecode1($recode1)->setRecode2($recode2)
                ->setRelation($synastryReportData['relation_id']);

            $synastryReportResultDetail = [];

            for ($i = $startTime; $i < $endTime; $i = strtotime('+1 year', $i))
            {
//                print_r('ID:' . $jobData['synastry_report_id'] . '开始计算：' . date('Y-m', $i) . PHP_EOL);
                $synastryReportResultDetail[] = $synastryReportLib->setStartTime($i)->getReportData();
            }

            // 实例化合盘报告解锁类
//            $synastryReportResultDetail = (new SynastryReportLib())->setRecode1($recode1)
//                ->setRecode2($recode2)
//                ->setRelation($synastryReportData['relation_id'])
//                ->setStartTime($synastryReportData['start_time'])
//                ->getReportData();
            // 获取合盘报告解锁结果
            $synastryReportResultDetailStr = \GuzzleHttp\json_encode($synastryReportResultDetail);
//            print_r('ID:' . $jobData['synastry_report_id'] . '结束计算：' . date('Y-m', $i) . PHP_EOL);
            // 更新合盘报告结果
            $SynastryReportModel->UpdateData(['status' => 2, 'update_time' => $now_time, 'content' => $synastryReportResultDetailStr], $synastryReportId);

            if ($synastryReportData['order_num'])
            {   // 更新订单缓存
                $OrdersModel->UpdateData($synastryReportData['order_num'], ['status' => 4, 'update_time' => $now_time], 4);
            }
            $res = true;
            $job->delete();
        }
        catch (Exception $e)
        {
            $res = false;
            // 合盘报告计算失败
            $logInfo .= ' 合盘报告计算失败: ' . $e->getMessage() . ' [' . $e->getFile() . ':' . $e->getLine() . ']';
        }

        if ($res === true && isset($jobData['push_switch']) && $jobData['push_switch'])
        {
            $pushData = ['id' => $synastryReportId, 'action' => 'synastry_report'];
            // 消息中心跳转地址
            $messageLink = Env::get('host.domain') . '/web/synastry_report/index?id=' . $synastryReportId . '&zhunle_not_show_nav=1&zhunle_nav_text_color=1&need_auth=1';

            if (isset($recode1['isself']) && $recode1['isself'])
            {   // 自己和别人的合盘信息
                $msgContent = "您购买的与{$recode2['name']}恋爱合盘报告已经计算完成，点击查看详情";
            } else
            {   // 其他人的合盘信息
                $msgContent = "您购买的{$recode1['name']}与" . ($recode2['isself'] ? '自己' : $recode2['name']) . '的恋爱合盘报告已经计算完成，点击查看详情';
            }

            // 消息中心添加信息
            $messageData = [
                'status' => 0,
                'is_read' => 0,
                'range' => $synastryReportData['uid'],
                'type' => 2,
                'reid' => 0,
                'cid' => 4,// 本命预测
                'title' => '合盘报告计算完成',
                'content' => $msgContent,
                'link' => $messageLink,
                'target' => 'link',
                'create_time' => $now_time
            ];
            try
            {
                (new MessageCenter())->pushMessage($synastryReportData['uid'], $messageData);
                // PUSH推送报告首页
                $pushRes = (new Push())->pushUserMsg($synastryReportData['uid'], $msgContent, $pushData);
                if (!$pushRes['success'])
                {
                    $logInfo .= '合盘报告计算完成,推送失败: ' . $pushRes['message'];
                }
            }
            catch (Exception $e)
            {
                $logInfo .= '合盘报告消息: ' . $e->getMessage() . ' [' . $e->getFile() . ':' . $e->getLine() . ']';
            }
        }
        $logInfo .= ' jobData:' . json_encode($jobData, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        print(date('Y-m-d H:i:s') . ' ' . $logInfo);
        Log::write($logInfo, 'log', true);
    }
}
